package helperx

import (
	"errors"

	"github.com/speps/go-hashids"
)

const salt string = "this_is_a_good_hash_id_salt"
const minLength int = 16

// HashIdEncode ID 转 HASH
func HashIdEncode(n int) (string, error) {
	hd := hashids.NewData()
	hd.Salt = salt
	hd.MinLength = minLength

	h, err := hashids.NewWithData(hd)
	if err != nil {
		return "", err
	}

	e, err := h.Encode([]int{n})
	if err != nil {
		return "", err
	}

	return e, nil
}

// HashIdDecode HASH 转 ID
func HashIdDecode(e string) (int, error) {
	hd := hashids.NewData()
	hd.Salt = salt
	hd.MinLength = minLength

	h, err := hashids.NewWithData(hd)
	if err != nil {
		return 0, err
	}
	d, err := h.DecodeWithError(e)
	if err != nil {
		return 0, err
	}

	if len(d) != 1 {
		return 0, errors.New("empty string")
	}

	return d[0], nil
}
